package manager;

import java.util.ArrayList;

import entity.Bid;
import exception.ValidationError;

//import java.sql.*;

/**
 * @author huangjm.2012, huiwensong.2012
 * 
 */
public class BidMgr {

	private DatabaseMgr dbMgr;

	public BidMgr() {
		dbMgr = new DatabaseMgr();
	}

	public void addBid(Bid bid) {

		String sql = "insert into student (userId, bidAmount, courseCode, sectionCode) values (?,?,?,?)";

		dbMgr.openAndUpdateAndClose(sql, bid.getStudent().getUserId(),
				bid.getBidAmount(), bid.getSection().getCourse()
						.getCourseCode(), bid.getSection().getSectionCode());
	}

	public void deleteBid(String userId, String courseCode, String sectionCode)
			throws ValidationError {

		String sql = "delete from bid where userId=? and courseCode=? and sectionCode=?";

		int numRowsAffected = dbMgr.openAndUpdateAndClose(sql, userId,
				courseCode, sectionCode);

		if (numRowsAffected < 1) {
			throw new ValidationError("no such bid");
		}
	}

	public void deleteAllBids() {
		dbMgr.openAndUpdateAndClose("delete from bid");
	}

	public ArrayList<Bid> retrieveAllBids() {

		String sql = "select * from bids_with_student_section_course order by userId ";

		return RetrieveBidUtil.retrieveMultipleBidsForQuery(dbMgr, sql);
	}

	public ArrayList<Bid> retrieveBidsForStudent(String userId) {

		String sql = "select * from bids_with_student_section_course "
				+ " where userId=? order by userId ";

		return RetrieveBidUtil.retrieveMultipleBidsForQuery(dbMgr, sql, userId);
	}

	public ArrayList<Bid> retrieveBidsForSection(String courseCode,
			String sectionCode) {

		String sql = "select * from bids_with_student_section_course "
				+ " where courseCode=? and sectionCode=? "
				+ " order by userId ";

		return RetrieveBidUtil.retrieveMultipleBidsForQuery(dbMgr, sql,
				courseCode, sectionCode);
	}

	public ArrayList<Bid> retrieveBidResultsForSection(String courseCode,
			String sectionCode) {

		String sql = "select * from bid_result_with_student_section_course "
				+ " where courseCode=? and sectionCode=? "
				+ " order by bidAmount desc, userId asc";

		return RetrieveBidUtil.retrieveMultipleBidsForQuery(dbMgr, sql,
				courseCode, sectionCode);
	}

}
